# coding:utf-8
# @Time      :2022/8/2312:34 AM
# @Author    :peiyu
# @FileName  :basepage
# @email     :web
# @Blog      :https://gitee.com/XXXXXXXXX

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if driver is not None:
            self.driver = driver
        else:
            options = Options()
            options.debugger_address = '127.0.0.1:9222'
            self.driver = webdriver.Chrome(options=options)

    def click(self, by, value):
        # todo: 异常处理
        try:

            self.find(by,value).click()
        except Exception as e:
            print("页面中没有找到text为%s的元素" % value)
            raise e


    def find(self, by, value):
        try:
        # todo: 异常处理
        # todo: 智能判断
        #     WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located((by, value)))
            self.wait_element(self.driver,by,value,10,type="visibility_of_element")
            return self.driver.find_element(by, value)
        except Exception as e:
            print("页面中没有找到text为%s的元素" % value)
            raise e

    def wait_element(self,by,value,times:int,type =None):
        if type=="visibility_of_element":#等待元素可见
            return  WebDriverWait(self.driver, times).until(expected_conditions.visibility_of_element_located((by, value)))
        if type=="presence_of_element":#等待元素存在
            return  WebDriverWait(self.driver,times).until(expected_conditions.presence_of_element_located((by, value)))